<?php
// +--
// | https://github.com/haojohnny
// | @Author: Johnny
// | Date: 2019-07-04 19:12
// | Remark:
// |

namespace wuwu\cosydevtool\command\make;

use think\console\Input;
use think\console\Output;
use think\facade\Db;
use think\console\Input\Argument;
use wuwu\cosydevtool\BaseMake;

class Validate extends BaseMake
{
    protected $type = 'validate';

    protected function configure()
    {
        $this->setName('cosy:validate')
            ->addArgument('name', Argument::REQUIRED, 'Please input your class name')
            ->addArgument('tableName', Argument::REQUIRED, 'Please input your table name')
            ->setDescription('创建一个validate验证器');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->executeBuild($input, $output);
    }
    
    // 填充模板
    public function buildClass($name)
    {
        $stub = $this->getStub();
        $namespace = trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\');
        $class = str_replace($namespace . '\\', '', $name);

        $validateName = $class.'Validate';


        $tableName = $this->input->getArgument('tableName');

        $columnsInfo = $this->getColumnsInfo($tableName);

        $search = [
            '{%namespace%}',
            '{%createTime%}',
            '{%className%}',
            '{%rule%}',
            '{%message%}',
            '{%scene%}',
            '{%validateName%}',
        ];

        $replace = [
            $namespace,
            date('Y-m-d H:i'),
            $class,
            $this->getRule($columnsInfo),
            $this->getMessage($columnsInfo),
            $this->getScene($columnsInfo),
            $validateName
        ];
        

        return str_replace($search, $replace, $stub);
    }

    /**
     * 获取模板
     * @return string
     */
    protected function getStub()
    {
        $path = __DIR__.DIRECTORY_SEPARATOR.'stubs'.DIRECTORY_SEPARATOR.$this->type.'.stub';
        return file_get_contents($path);
    }

    protected function getPathName(string $name): string
    {
        $name = str_replace('app\\', '', $name);
//        if(config('route.controller_suffix') == true){
            $name = $name.'Validate';
//        }
        return $this->app->getBasePath() . ltrim(str_replace('\\', '/', $name), '/') . '.php';
    }

    /**
     * @param $tableName
     * @return mixed
     */
    public function getColumnsInfo($tableName)
    {
        $arr = explode('.', $tableName);
        $dbName = '';
        $tableName = $arr[0];
//        if (count($arr)) {
//            list($dbName, $tableName) = $arr;
//        }
        $sql = "SELECT COLUMN_NAME,COLUMN_KEY,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,COLUMN_COMMENT,IS_NULLABLE 
                FROM INFORMATION_SCHEMA.Columns 
                WHERE table_name='{$tableName}'";

        if (!empty($dbName)) {
            $sql = "{$sql} AND TABLE_SCHEMA = '{$dbName}'";
        }

        return Db::query($sql);
    }

    public function getRule($columnsInfo)
    {
        $rule = '';

        foreach ($columnsInfo as $key => $column) {
            $rules = $this->parseColumnToRule($column);
            $columnRule = implode('|', $rules);

$rule .= <<<EOF
'{$column['COLUMN_NAME']}' => '{$columnRule}',
        
EOF;
        }

        return $rule;
    }

    /**
     * 解析字段验证规则
     * @param $column
     * @return array 规则数组
     */
    public function parseColumnToRule($column)
    {
        // 默认必填
        $rules[] = 'require';

        switch ($column['DATA_TYPE']) {
            case 'int':
                $rules[] = 'number';
                break;
            case 'char':
                $rules[] = 'length:'.$column['CHARACTER_MAXIMUM_LENGTH'];
                break;
            case 'varchar':
                $rules[] = 'max:'.$column['CHARACTER_MAXIMUM_LENGTH'];
                break;
            case 'datetime':
                $rules[] = 'dateFormat:Y-m-d H:i:s';
                break;
            case 'date':
                $rules[] = 'dateFormat:Y-m-d';
                break;
            case 'time':
                $rules[] = 'dateFormat:H:i:s';
                break;
            // TODO: and more
            default:
        }

        return $rules;
    }

    /**
     * 解析规则为错误信息提示
     * @param $ruleName
     * @return string
     */
    public function parseRoleToMessage($ruleName)
    {
        switch ($ruleName) {
            case 'require':
                $roleMessage = '必须填写';
                break;
            case 'number':
                $roleMessage = '数据格式必须为数字';
                break;
            case 'dateFormat:Y-m-d H:i:s':
                $roleMessage = '必须为yyyy-mm-dd hh:ii:ss格式';
                break;
            case 'dateFormat:Y-m-d':
                $roleMessage = '必须为yyyy-mm-dd格式';
                break;
            case 'dateFormat:H:i:s':
                $roleMessage = '必须为hh:ii:ss格式';
                break;
            default:
                list($ruleName, $num) = explode(':', $ruleName);
                switch ($ruleName) {
                    case 'length':
                        $roleMessage = "长度必须为{$num}个字符";
                        break;
                    case 'max':
                        $roleMessage = "最大长度为{$num}个字符";
                        break;
                    default:
                        $roleMessage = '数据有误';
                }
        }

        return $roleMessage;
    }

    public function getMessage($columnsInfo)
    {
        $message = '';

        foreach ($columnsInfo as $column) {
            $roles = $this->parseColumnToRule($column);
            foreach ($roles as $ruleName) {
                $msg = $this->parseRoleToMessage($ruleName);

                if ($pos = strpos($ruleName, ':')) {
                    $ruleName = substr($ruleName, 0, $pos);
                }

                $message .= <<<EOF
'{$column['COLUMN_NAME']}.{$ruleName}' => '{$column['COLUMN_COMMENT']}{$msg}',
        
EOF;
            }
        }

        return $message;
    }

    public function getScene($columnsInfo)
    {
        $scene = '';
        $insert = [];
        $update = [];

        foreach ($columnsInfo as $column) {
            if ($column['COLUMN_KEY'] == 'PRI') {
                $update[] = "'{$column['COLUMN_NAME']}'";
            } else {
                $insert[] = "'{$column['COLUMN_NAME']}'";
                $update[] = "'{$column['COLUMN_NAME']}'";
            }
        }
        $insert = implode($insert, ', ');
        $update = implode($update, ', ');
        $scene .= <<<EOF
        'insert' => [{$insert}],
                'update' => [{$update}],        
        EOF;

        return $scene;
    }
}